package com.infore.airsupervise.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import org.json.JSONException;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import static android.R.id.list;

/**
 * JSON解析工具类：依赖FastJson框架
 */
public class JSONUtil {

	/**
	 * 解析Bean
	 * @param dataMap
	 * @param keyName
	 * @param cls
	 * @param <T>
	 * @return
	 */
	public static <T> T parseBean(Map<String, ?> dataMap, String keyName, Class<T> cls) {
		JSONObject jsObj = (JSONObject) dataMap.get(keyName);
		T bean = JSON.parseObject(jsObj.toString(), cls);
		return bean;
	}

	/**
	 * 解析BeanList
	 * @param dataMap
	 * @param keyName
	 * @param cls
	 * @param <T>
     * @return
     */
	public static <T> List<T> parseList(Map<String, ?> dataMap, String keyName, Class<T> cls) {
		JSONArray jsArr = (JSONArray) dataMap.get(keyName);
		List<T> resultList = new ArrayList<>();
		for (int i = 0; i < jsArr.size(); i++) {
			String joStr = jsArr.getJSONObject(i).toString();
			T t = JSON.parseObject(joStr, cls);
			resultList.add(t);
		}
		return resultList;
	}

	public static <T> String toJSONString( List<T> list){
		String str_json = JSONArray.toJSONString(list,true);
		return str_json;
	}

	public static <T> String toJSOnString(T t){
		String str_json = JSON.toJSONString(t,true);
		return str_json;
	}

	public static <T> List<T> parseJSONArrayString(String str_json,Class<T> cls){
		List<T> resultList = JSONArray.parseArray(str_json,cls);
		return resultList;
	}
	public  static <T> T parseJSONString(String str_json,Class<T> cls){
		T t = JSON.parseObject(str_json,cls);
		return t;
	}
}
